<template>
  <div>
    <div v-for="(item, item_index) in stats.children" :key="item_index">
      <!-- 概况 -->
      <div class="overview text-center mb-10px">
        <div class="text-333 font-normal">
          <span>总得分：</span>
          <span
            class="font-semibold"
            :class="`text-${getScoreClass(stats.totalStudentScore / stats.totalQuestionScore)}`"
            style="font-size: 0.5rem; line-height: 0.7rem"
            >{{ stats.totalStudentScore }}</span
          >
          <span :class="`text-${getScoreClass(stats.totalStudentScore / stats.totalQuestionScore)}`"
            >分</span
          >
          <span>/{{ stats.totalQuestionScore }}分</span>
        </div>
      </div>
      <Stem
        master="wqbook_detail_english"
        :data="item.stem"
        :answer="item.answer"
        :student-answer="item.studentAnswer"
        :readonly="true"
      />
      <div class="hr my-30px" v-show="item_index < stats.children.length - 1"></div>
    </div>
  </div>
</template>

<script>
import Stem from '@/components/question/stem'
import { formatQuestionStem } from '@/utils/question'
import Mixin from '../mixin'

export default {
  components: {
    Stem
  },
  mixins: [Mixin],
  inject: ['_addTagClickHandler', '_removeTagClickHandler'],
  props: {
    question: {
      type: Object,
      default: () => {}
    }
  },
  data() {
    return {}
  },
  computed: {
    stats() {
      const { questionId, answerRecord, studentScore, questionScore } = this.question
      const questionIds = [questionId]
      const stemQuestions = [this.question]
      const remoteStudentAnswer = [answerRecord]

      return {
        children: questionIds.map((id, index) => {
          const startIndex = index + (index + 1)
          const q = stemQuestions.find((sq) => sq.questionId === id)
          const { questionId } = q
          const stem = q.stem
          const {
            info: { audio: audioSrc }
          } = stem
          const answer = q.answer
          const studentAnswer = remoteStudentAnswer[index]

          const templateSpeaker = `<span class="append-speaker"><img src="static/icons/speaker.png" data-question-id="${questionId}" data-audio-src="${audioSrc}" /></span>`
          const {
            info: { st_nr, xtlist = [] }
          } = stem

          let sqs = []
          xtlist.forEach((i, index) => {
            const { xt_nr = '', xxlist = [] } = i
            const templateQuestion = xt_nr.replace(/ets_th[0-9]\s/, `${startIndex + index}.`)
            let templateScore = `<span class="text-FF4040">（未作答）</span>`
            try {
              const { anSqs } = studentAnswer
              const anStudent = anSqs[index].ans[0].anStudent
              const score = anSqs[index].ans[0].studentScore
              const totalScore = anSqs[index].ans[0].questionScore

              if (!totalScore) throw ''

              templateScore = `<span class="text-${this.getScoreClass(
                score / totalScore
              )}">（得分：${anStudent ? `${score}分` : '未作答'}/${totalScore}分）</span>`
            } catch (error) {}
            const html = `<div class="mt-${
              index === 0 ? 10 : 18
            }px">${templateQuestion}${templateScore}</div>`
            sqs.push({
              html,
              og: {
                ogOps: xxlist.map((item, index) => {
                  const { xx_mc, xx_nr } = item

                  return {
                    index: xx_mc,
                    html: `${xx_mc}.${xx_nr}`
                  }
                }),
                cols: xxlist.length
              },
              sqs: [],
              type: '选择题'
            })
          })

          return {
            questionId,
            stem: formatQuestionStem({
              html: `<div><p><span>听下面一段对话，回答第${startIndex}至第${
                startIndex + 1
              }小题。现在，你有10秒钟的时间阅读这两道小题。</span>${templateSpeaker}</p><p>${st_nr}</p></div>`,
              og: null,
              sqs,
              type: '英语听说-听后选择'
            }),
            answer,
            studentAnswer
          }
        }),
        totalStudentScore: studentScore ? studentScore : 0,
        totalQuestionScore: questionScore ? questionScore : 0
      }
    }
  },
  mounted() {
    this._addTagClickHandler('img', this.handleImgClick)
  },
  beforeDestroy() {
    this._removeTagClickHandler('img', this.handleImgClick)
  },
  methods: {
    handleImgClick(node) {
      const { currentSrc = '' } = node
      if (currentSrc.indexOf('speaker.png') != -1) {
        const { audioSrc, questionId } = node.dataset

        if (!audioSrc || audioSrc === 'undefined') {
          this.$message.error('未作答')
          return
        }

        if (questionId === this.question.questionId) {
          this.playAudio(node, audioSrc)

          const components = this.$parent.$parent.$refs
          for (let key in components) {
            if (Array.isArray(components[key]) && components[key].length > 0) {
              const component = components[key][0]
              const {
                question: { questionId: _questionId }
              } = component
              if (questionId != _questionId) {
                component.audioPlayer.pause()
              }
            }
          }
        }
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.overview {
  font-size: 20px;
}

/deep/ .append-speaker {
  display: inline-block;
  width: 46px;
  height: 46px;
  position: relative;

  img {
    width: 46px;
    height: 46px;
    position: absolute;
    top: 50%;
    transform: translateY(-24%);
  }

  .playing {
    @keyframes play {
      0% {
        opacity: 0.5;
      }

      25% {
        opacity: 0.25;
      }

      50% {
        opacity: 0.5;
      }

      75% {
        opacity: 0.75;
      }

      100% {
        opacity: 1;
      }
    }

    animation: play 1s ease-in-out infinite backwards;
  }
}

.hr {
  height: 1px;
  background: #eee;
}
</style>
